<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
/**
 * Class CouponReceive
 * Desc  领券优惠券控制器
 * Create on 2025/4/28 16:00
 * Create by wangyafang
 */

namespace app\api\controller\wddj\marketing;


use app\api\model\wddj\User;
use app\common\controller\Api;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

class CouponReceive extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    protected $model = null;
    protected $wechat_id = null;
    protected $couponModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\wddj\marketing\CouponReceive();
        $this->wechat_id = User::getWechatId($this->auth->id);
        if (empty($this->wechat_id)) {
            $this->error('用户信息不存在');
        }
        $this->couponModel = new \app\api\model\wddj\marketing\Coupon();
    }

    /**
     * Desc 领取优惠券
     * Create on 2025/4/28 16:01
     * Create by wangyafang
     */
    public function receive()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $coupon_id = $this->request->post('coupon_id');
        if (empty($coupon_id)) {
            $this->error('参数错误');
        }

        $couponObj = $this->couponModel->get($coupon_id);
        if (!$couponObj) {
            $this->error('优惠券不存在');
        }

        $where['wechat_id'] =$this->wechat_id;
        $where['coupon_id'] = $coupon_id;
        if($this->model->where($where)->find()) {
            $this->error('已领过优惠券');
        }

        $current_date =date("Y-m-d").' 23:59:59';//当前时间

        $create_data = [
            'coupon_id'=>$coupon_id,
            'discount_price'=>$couponObj['discount_price'],
            'coupon_name'=>$couponObj['name'],
            'wechat_id'=>$this->wechat_id,
            'user_id'=>$this->auth->id,
            'exchange'=>2,
            'expire_type'=>$couponObj['expire_type'],
        ];
        if ($couponObj['expire_type'] == 1) {
            if($couponObj['expire_day'] == 1) {
                $expire_time=strtotime($current_date);
            } else {
                $couponObj['expire_day'] = $couponObj['expire_day'] -1;
                $expiretime=strtotime(date("Y-m-d") . '+'.$couponObj['expire_day'].' day');
                $current_date = date("Y-m-d",$expiretime).' 23:59:59';
                $expire_time=strtotime($current_date);
            }
            $create_data['expire_time'] = $expire_time;
        } else {
            $create_data['expire_start_time'] = $couponObj['expire_start_time'];
            $create_data['expire_end_time'] = $couponObj['expire_end_time'];
        }

        Db::startTrans();
        try {
            $this->model->data($create_data);
            $this->model->allowField(true)->save();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('领取成功');
    }

    /**
     * Desc 我的卡券
     * Create on 2025/4/28 16:27
     * Create by wangyafang
     */
    public function my_coupon()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->get();
        $page = isset($param['page']) ? $param['page'] : '';
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $place_order = (isset($param['place_order']) && !empty($param['place_order'])) ? $param['place_order'] : '';

        $count = $this->model->where('wechat_id', $this->wechat_id)
            ->where('exchange','2')
            ->where(function ($query) use($place_order) {
                $time = time();

                // 第一个条件：expire_type = 1 且 expire_time >= 当前时间
                $dayQuery = [
                    'expire_type' => 1,
                    'expire_time' => ['>=', $time],
                ];

                if ($place_order) {
                    // 第二个条件：expire_type = 2 且 expire_start_time <= 当前时间 且 expire_end_time >= 当前时间
                    $dateTimeQuery = [
                        'expire_type' => 2,
                        'expire_start_time' => ['<=', $time],
                        'expire_end_time' => ['>=', $time],
                    ];
                } else {
                    // 第二个条件：expire_type = 2 且 expire_start_time >= 当前时间
                    $dateTimeQuery = [
                        'expire_type' => 2,
                        'expire_end_time' => ['>=', $time],
                    ];
                }


                // 使用括号确保逻辑关系正确
                $query->where(function ($q) use ($dayQuery) {
                    $q->where($dayQuery);
                })
                    ->whereOr(function ($q) use ($dateTimeQuery) {
                        $q->where($dateTimeQuery);
                    });
            })
            ->count();

        $list = $this->model->where('wechat_id',$this->wechat_id)
            ->where('exchange','2')
            ->where(function ($query) use($place_order) {
                $time = time();

                // 第一个条件：expire_type = 1 且 expire_time >= 当前时间
                $dayQuery = [
                    'expire_type' => 1,
                    'expire_time' => ['>=', $time],
                ];

                if ($place_order) {
                    // 第二个条件：expire_type = 2 且 expire_start_time <= 当前时间 且 expire_end_time >= 当前时间
                    $dateTimeQuery = [
                        'expire_type' => 2,
                        'expire_start_time' => ['<=', $time],
                        'expire_end_time' => ['>=', $time],
                    ];
                } else {
                    // 第二个条件：expire_type = 2 且 expire_start_time >= 当前时间
                    $dateTimeQuery = [
                        'expire_type' => 2,
                        'expire_end_time' => ['>=', $time],
                    ];
                }


                // 使用括号确保逻辑关系正确
                $query->where(function ($q) use ($dayQuery) {
                    $q->where($dayQuery);
                })
                    ->whereOr(function ($q) use ($dateTimeQuery) {
                        $q->where($dateTimeQuery);
                    });
            })
            ->page($page,$limit)
            ->field('coupon_id id,coupon_name name,discount_price,expire_time,
            expire_type,expire_start_time,expire_end_time')
            ->select();
        foreach ($list as &$v) {
            if ($v['expire_type'] == 1) {
                $v->expire_date = date("Y-m-d",$v->expire_time).'到期';
                $v->immediate_use = 1;
            } else {
                $v->expire_date = date("m-d H:i:s",$v->expire_start_time).'-'.date("m-d H:i:s",$v->expire_end_time);
                $v->immediate_use = ($v->expire_start_time <= time()) ?  1 : 2;
            }

            $v->hidden(['expire_time','expire_type','expire_start_time','expire_end_time']);
        }

        $this->success('请求成功',['total' => $count,'data' => $list]);
    }

    /**
     * Desc 领券中心
     * Create on 2025/5/6 15:24
     * Create by wangyafang
     */
    public function coupon_center()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->get();
        $page = isset($param['page']) ? $param['page'] : '';
        $limit = isset($param['limit']) ? $param['limit'] : 10;

        $receive_id_array = $this->model
            ->where('wechat_id',$this->wechat_id)
            ->column('coupon_id');

        $count = $this->couponModel
            ->where('id','not in',$receive_id_array)
            ->where(function($query) {
                $time = time();
                $query->where('expire_type', '<>', 2)
                    ->whereOr(function($q) use ($time) {
                        $q->where('expire_type', 2)
                            ->where('expire_end_time', '>=', $time);
                    });
            })
            ->count();

        $list = $this->couponModel->where('id','not in',$receive_id_array)
            ->page($page,$limit)
            ->field('id,name,discount_price')
            ->where('status','normal')
            ->where(function($query) {
                $time = time();
                $query->where('expire_type', '<>', 2)
                    ->whereOr(function($q) use ($time) {
                        $q->where('expire_type', 2)
                            ->where('expire_end_time', '>=', $time);
                    });
            })
            ->order('weigh desc,id desc')
            ->select();

        $this->success('请求成功',['total' => $count,'data' => $list]);
    }


}



 